package com.xxx.service.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xxx.common.IdWorkerManage;
import com.xxx.common.dto.Page;
import com.xxx.common.dto.Pagination;
import com.xxx.dao.SysRoleMenuDao;
import com.xxx.model.SysRoleMenu;
import com.xxx.service.SysRoleMenuService;
import com.xxx.service.SysUserRoleService;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {
	
	@Autowired
	private SysRoleMenuDao sysRoleMenuDao;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Override
	@Transactional
	public long saveOrUpdate(SysRoleMenu sysRoleMenu) throws Exception {
		if(sysRoleMenu.getId() == null){
			sysRoleMenu.setId(IdWorkerManage.getId());
			return sysRoleMenuDao.save(sysRoleMenu);
		}
		return sysRoleMenuDao.update(sysRoleMenu);
	}

	@Override
	@Transactional
	public boolean delete(long id) throws Exception{
		return sysRoleMenuDao.delete(id);
	}

	@Override
	public SysRoleMenu getEntity(long id) throws Exception{
		return sysRoleMenuDao.getEntity(id);
	}

	@Override
	public int getCount(Map<String, Object> whereMap) {
		return sysRoleMenuDao.getCount(whereMap);
	}
	
	@Override
	public List<SysRoleMenu> getList(Map<String, Object> whereMap) {
		return sysRoleMenuDao.getList(whereMap);
	}

	@Override
	public List<SysRoleMenu> getList(Map<String, Object> whereMap, Pagination pagination) {
		return sysRoleMenuDao.getList(whereMap, pagination);
	}
	
	@Override
	public Page<SysRoleMenu> getPage(Map<String, Object> whereMap, Pagination pagination) {
		int count = this.getCount(whereMap);
		if(count > 0){
			List<SysRoleMenu> list = this.getList(whereMap, pagination);
			return new Page<SysRoleMenu>(pagination.getCurrentPage(), pagination.getPageSize(), count, list);
		}
		return new Page<SysRoleMenu>(pagination.getCurrentPage(), count);
	}

	@Override
	public Map<Long, Long> getRoleMenuMap(long roleid) {
		Map<String, Object> whereMap = new HashMap<>();
		whereMap.put("roleid", roleid);
		List<SysRoleMenu> list = this.getList(whereMap);
		Map<Long,Long> map = new HashMap<>();
		for (SysRoleMenu sys_RoleMenu : list) {
			map.put(sys_RoleMenu.getMenuid(),sys_RoleMenu.getId());
		}
		return map;
	}

	@Override
	public Set<Long> getUserRoleMenu(long userid) {
		Set<Long> userRoleSet = sysUserRoleService.getUserRoleSet(userid);
		Set<Long> roleMenuSet = new HashSet<>();
		List<SysRoleMenu> list = this.getList(null);
		for (SysRoleMenu sysRoleMenu : list) {
			if(userRoleSet.contains(sysRoleMenu.getRoleid())){
				roleMenuSet.add(sysRoleMenu.getMenuid());
			}
		}
		return roleMenuSet;
	}
}
